import React, { Component } from 'react'
import { Link } from 'react-router-dom'
import { observer, inject } from 'mobx-react'
import { Table, Tooltip, Menu, Tag } from 'antd'
import ItemScheduleForm from './ItemScheduleForm'
import './itemSchedule.css'

// Global Component
@inject('itemStore', 'store')@observer
class ItemScheduleComponent extends Component {
  constructor(props){
    super(props)
    const { cacheData } = props.itemStore;
    this.state = {
      pagination: {
        defaultCurrent: props.itemStore.page || 1,
        defaultPageSize: props.itemStore.pageSize || 10,
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100'],
        showTotal: () => `共${this.props.itemStore.total}条数据`,
      },
      searchData: props.itemStore.cacheData,
      widowWidth: document.body.offsetWidth,
      widowHeight: document.body.offsetHeight,
      categoryId: cacheData.categoryId || '',
      menuOpenKeys: props.itemStore.menuOpenKeys.slice(),
      menuSelectedKeys: cacheData.categoryId ? [cacheData.categoryId] : [],
    }
  }

  componentWillMount() {
  }

  componentDidMount() {
    const { getCategoryListMenu, getProductList, cacheData, categoryListMenu, productList } = this.props.itemStore;
    let _cacheData = { ...cacheData }
    delete _cacheData.categoryId
    window.addEventListener('resize', this.onWindowResize)
    if(categoryListMenu.length === 0) {
      getCategoryListMenu(_cacheData)
    }
    if(productList.length === 0) {
      //getProductList(cacheData)
    }
  }

  componentWillReceiveProps(nextProps) {
  }

  componentWillUnmount() {
    window.removeEventListener('resize', this.onWindowResize)
  }

  onWindowResize = () => {
    this.setState({
      widowWidth: document.body.offsetWidth,
      widowHeight: document.body.offsetHeight
    })
  }

  handlePageChange = (pagination) => {
    const { searchData, categoryId } = this.state;
    this.state.pagination.current = pagination.current;
    this.props.itemStore.getProductList({
      ...searchData,
      categoryId: categoryId,
      page: pagination.current,
      pageSize: pagination.pageSize,
    })
    this.setState({
      pagination: this.state.pagination
    })
  }

  handleSearchSubmit = (params) => {
    this.props.itemStore.getProductList({categoryId: this.state.categoryId, ...params})
    this.props.itemStore.getCategoryListMenu(params)
    this.state.pagination.current = 1;
    this.setState({
      searchData: params,
      pagination: this.state.pagination
    })
  }

  handleCategorySelect = (e) => {
    //const { searchData } = this.state;
    this.state.pagination.current = 1;
    let searchData = this.formRef.props.form.getFieldsValue();
    if(searchData.status === 'all') {
      delete searchData.status
    }
    this.setState({
      categoryId: e.key,
      menuSelectedKeys: [e.key],
      pagination: this.state.pagination
    })
    this.props.itemStore.getProductList({ ...searchData, categoryId: e.key})
    this.props.itemStore.getCategoryListMenu(searchData)
  }

  handleMenuOpen = (e) => {
    this.setState({
      menuOpenKeys: e
    })
    this.props.itemStore.saveCacheData({menuOpenKeys: e})
  }

  handleFormReset = () => {
    this.props.itemStore.getProductList({})
    this.props.itemStore.getCategoryListMenu({})
    this.state.pagination.current = 1;
    this.setState({
      searchData: {},
      categoryId: "",
      menuOpenKeys: [],
      menuSelectedKeys: [],
      pagination: this.state.pagination
    })
    this.props.itemStore.saveCacheData({categoryId: '', menuOpenKeys: []})
  }

  //分类长度超过限制，显示提示文字
  handleLabelTooltip = (label, limit, total) => {
    if(label.replace(/[^\u0000-\u00ff]/g,"aa").length/2 > limit + 1) {
      let bytesCount = 0, subNum = 0;
      for (let i = 0; i < label.length; i ++) {
        if (/^[\u0000-\u00ff]$/.test(label.charAt(i))) { //匹配双字节
          bytesCount += 1;
        } else {
          bytesCount += 2;
        }
        if(bytesCount > limit*2) {
          break;
        }
        subNum += 1;
      }
      return (<Tooltip placement="right" title={label}>
        {`${label.substring(0,subNum)}...${total !== undefined ? ' (' + total + ')' : ''}`}
      </Tooltip>)
    } else {
      return `${label}${total !== undefined ? ' (' + total + ')' : ''}`;
    }
  }

  /*searchFormRef = (form) => {
    this.form = form;
  }*/

  render() {
    const tagStyle = { width: 54, textAlign: 'center'}
    const columns = [
      {
        title: '商品编码',
        dataIndex: 'itemCode',
        key: 'itemCode',
        width: 80,
      }, {
        title: '商品名称',
        dataIndex: 'goodsName',
        key: 'goodsName',
        width: 220,
      }, {
        title: '英文名称',
        dataIndex: 'goodsEnName',
        key: 'goodsEnName',
        width: 120,
        render: (text, record) => (
            <Tooltip title={record.goodsEnName}>
              <span>{`${record.goodsEnName.substring(0, 8)}...`}</span>
            </Tooltip>
        )
      }, {
        title: '商品条码',
        dataIndex: 'barcode',
        key: 'barcode',
        width: 150,
      }, {
        title: '销售规格',
        dataIndex: 'specUnit',
        key: 'specUnit',
        width: 120,
        render: (text, record) => <span>{`${record.spec}/${record.unit}`}</span>
      }, {
        title: '长x宽x高(cm)',
        dataIndex: 'length',
        key: 'length',
        width: 100,
        render: (text, record) => <span>{`${record.length}x${record.width}x${record.height}`}</span>
      }, {
        title: '重量(g)',
        dataIndex: 'weight',
        key: 'weight',
        width: 80,
      }, {
        title: '属性',
        dataIndex: 'itemTypeName',
        key: 'itemTypeName',
        width: 80,
      }, {
        title: '状态',
        dataIndex: 'status',
        key: 'status',
        width: 100,
        render: (text, record) => (
          <span>
            {text === 0 ? <Tag color="orange" style={tagStyle}>{record.statusName}</Tag> : null}
            {text === 1 ? <Tag color="green" style={tagStyle}>{record.statusName}</Tag> : null}
            {text === -1 ? <Tag color="red" style={tagStyle}>{record.statusName}</Tag> : null}
          </span>
        )
      }, {
        title: '操作',
        key: 'action',
        fixed: this.state.widowWidth > 1360 ? false : 'right',
        width: 100,
        render: (text, record) => (
          <span>
            <Link to={`/item/modify/${record.itemId}`}>修改信息</Link>
          </span>
        ),
      }
    ]
    const { loading, productList, total, handleCategoryData, categoryListMenu, cacheData } = this.props.itemStore
    const { categoryId, menuSelectedKeys, menuOpenKeys, widowHeight } = this.state
    const pagination = Object.assign({total: total}, this.state.pagination)
    return (
      <div >
        {this.props.store.collapse ?
            <h2 style={{marginBottom: 16, flex: '0 0 auto'}}>
              <Link to="/item/schedule">商品主档管理</Link>
            </h2> : null
        }
        <ItemScheduleForm wrappedComponentRef={(inst) => this.formRef  = inst}
                          history={this.props.history}
                          categoryId={categoryId}
                          defaultValues={cacheData}
                          onSearch={this.handleSearchSubmit}
                          onReset={this.handleFormReset}/>
        <div style={{display: 'flex', position: 'relative'}}>
          <div style={{flex: '0 0 auto', width: 190, maxHeight: widowHeight - 240, overflowY: 'scroll'}}>
            <Menu mode="inline" onSelect={this.handleCategorySelect} onOpenChange={this.handleMenuOpen}
                  openKeys={menuOpenKeys} selectedKeys={menuSelectedKeys}>
              {handleCategoryData(categoryListMenu).map(item=>
                <Menu.SubMenu key={item.value}
                              title={`${this.handleLabelTooltip(item.label, 7)}`}>
                    {item.children.map(_item =>
                      <Menu.Item key={_item.value}>
                        {this.handleLabelTooltip(_item.label, 5, _item.total)}
                      </Menu.Item>)}
                </Menu.SubMenu>
              )}
            </Menu>
          </div>
          <div ref='tableRapper' className="tableRapper">
            <Table style={{width: '100%', minHeight: 450}} scroll={{x: 1100, y: widowHeight - 290}}
                   loading={loading}
                   columns={columns}
                   dataSource={productList.slice()}
                   pagination={pagination}
                   onChange={(pagination) => this.handlePageChange(pagination)}/>
          </div>
        </div>
      </div>
    )
  }
}
export default ItemScheduleComponent
